package com.mikufufu.blog.common;

import com.mikufufu.blog.common.enums.ModuleType;
import com.mikufufu.blog.common.enums.OperationType;
import com.mikufufu.blog.model.entity.OperateLog;
import com.mikufufu.blog.model.event.LogEvent;
import com.mikufufu.blog.security.utils.AuthUtils;
import com.mikufufu.blog.utils.IpUtil;
import com.mikufufu.blog.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Service
public class BaseService {

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    /**
     * 保存日志
     * @param type 操作类型
     * @param module 模块
     * @param content 内容
     * @param success 成功与否
     */
    public void saveLog(OperationType type, ModuleType module, String content, String params, boolean success) {
        OperateLog operateLog = new OperateLog();
        String username = AuthUtils.getUsername();
        HttpServletRequest request = getRequest();
        if (request != null){
            operateLog.setIp(IpUtil.getIpAddress(request));
            operateLog.setUrl(request.getRequestURI());
        }
        operateLog.setParams(params);
        operateLog.setOperator(StringUtils.isBlank(username)?"anonymousUser":username);
        operateLog.setOperateType(type.getType());
        operateLog.setRemark(content);
        operateLog.setStatus(success?1:0);
        operateLog.setOperateTime(new Date());
        operateLog.setModule(module.getType());
        eventPublisher.publishEvent(new LogEvent(operateLog));
    }

    /**
     * 获取当前请求
     * @return 当前请求
     */
    private HttpServletRequest getRequest() {
        // 从当前请求中获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes instanceof ServletRequestAttributes) {
            return ((ServletRequestAttributes) requestAttributes).getRequest();
        }
        return null;
    }
}
